void solve()
{
  int n, k;
  cin >> n >> k;

  map<int, vi> cnt, cnt2;
  map<string, int> id;
  vector<string> s(n + 1);
  vi v(n + 1), hs1(n + 1), hs2(n + 1);
  rep(i, 1, n) {
    cin >> s[i] >> v[i];
  }

  int idx = 0;
  auto f = [&](string &t) {
    if (!id.count(t)) {
      id[t] = idx++;
    }
    return id[t];
  };  

  rep(i, 1, n) {
    hs1[i] = f(s[i]);
    string t = s[i];
    reverse(all(t));
    hs2[i] = f(t);
    if (hs1[i] != hs2[i]) {
      cnt[hs1[i]].pb(i);
    } else {
      cnt2[hs1[i]].pb(i);
    }
  }

  ll ret = 0;
  for (auto &[x, vec]: cnt) {
    sort(all(vec), [&](int &x, int &y){
      return v[x] < v[y];
    });
  }
  for (auto &[x, vec]: cnt2) {
    sort(all(vec), [&](int &x, int &y){
      return v[x] < v[y];
    });
  }

  ll res = 0, ans = 0;
  vi mat(n + 1);
  
  auto add = [&](int p, int q) {
    mat[p] = q, mat[q] = p;
    res += v[p] + v[q];
  };

  auto get = [&](vi &vec) {
    while (sz(vec) && mat[vec.back()]) {
      vec.pop_back();
    }
    return (sz(vec)) ? vec.back() : -1;
  };

  int neg = 0;
  rep(i, 1, n) {
    if (hs1[i] == hs2[i]) {
      continue;
    }
    auto &vec1 = cnt[hs1[i]];
    auto &vec2 = cnt[hs2[i]];
    while (sz(vec1) && sz(vec2)) {
      int p = get(vec1);
      if (p == -1) {
        break;
      }
      mat[p] = true;
      int q = get(vec2);
      if (q == -1) {
        mat[p] = 0;
        break;
      }
      if (v[p] + v[q] > 0) {
        add(p, q);
      } else {
        mat[p] = mat[q] = 0;
        break;
      }
    }
  }
  for (auto &[x, y]: cnt2) {
    while (sz(y) >= 2) {
      int p = get(y);
      if (p == -1) {
        break;
      }
      mat[p] = 1;
      int q = get(y);
      if (q == -1) {
        mat[p] = 0;
        break;
      }
      if (v[p] + v[q] > 0) {
        neg = min(neg, v[p]);
        neg = min(neg, v[q]);
        add(p, q);
      } else {
        mat[p] = mat[q] = 0;
        break;
      }
    }
  }

  ans = res - neg;
  rep(i, 1, n) {
    if (hs1[i] == hs2[i] && !mat[i]) {
      ans = max(ans, res + v[i]);
    }
  }
  cout << ans;
}